var express = require('express');
var AdminUserRouter = express.Router();
// 引入数据库连接池
const db = require('../db/index');
//图片上传模块
const multer  = require('multer')
const upload = multer({ dest: 'public/avataruploads/' })

AdminUserRouter.post('/adminapi/user/add',upload.single('avatar'),function(req, res, next) {
    const avatar = req.file?`/avataruploads/${req.file.filename}`:""
    console.log(req.body);
    const { username:account, name, password, role, introduction } = req.body;
    console.log(account);
    // 检查用户是否已经存在
    const checkSql = 'SELECT * FROM admin_user_list WHERE account = ?';
    db.query(checkSql, [account])
    .then(results => {
        // console.log(results);
        if (results[0].length > 0) {
            // 用户已经存在
            console.log('用户已经存在');
            
            return res.send({
                code: 500,
                msg: '用户已存在',
                data: null
            });
        }
        // 用户不存在，执行插入操作
        // 构建 SQL 插入语句
        const sql = 'INSERT INTO admin_user_list (account, password, name, avatar, role, introduction) VALUES (?, ?, ?, ?, ?, ?)';
        const values = [account, password, name, avatar, Number(role), introduction];
        // 执行 SQL 插入操作
        db.query(sql, values)
            .then(result => {
                // console.log(result);
                res.send({
                    code: 200,
                    msg: '用户添加成功',
                    data: {}
                });
            })
            .catch(err => {
                console.error(err);
                res.status(500).send({
                    code: 500,
                    msg: '服务器错误',
                    data: null
                });
            });
    })
    .catch(err => {
        console.error(err);
        res.status(500).send({
            code: 500,
            msg: '服务器错误',
            data: null
        });
    });
});
AdminUserRouter.get('/adminapi/user/list',function(req, res, next) {
     // 构建 SQL 查询语句，排除 password 字段
     const sql = 'SELECT id, account, name, avatar, role, introduction FROM admin_user_list';

     // 执行 SQL 查询操作
     db.query(sql)
         .then(result => {
            // 处理查询结果，拼接头像字段的端口号
            const users = result[0].map(user => {
                return {
                    ...user,
                    avatar: `http://localhost:3001${user.avatar}`
                };
            });
            // 返回查询结果给前端
            res.send({
                code: 200,
                msg: '获取用户列表成功',
                data: {
                    list: users
                }
            });
            
         });
});


module.exports = AdminUserRouter;